import { useEffect, useState } from 'react';
import { assetListChildManageServices } from '../services';
import { message } from 'antd';

/**
 * 处理资产列表异步加载数据
 * @param dataRows 接口返回资产数据
 * @param dataSourceTable 处理后资产数据
 * @param setDataSourceTable 保存处理后的资产数据
 * @param tableExpantKeys 资产展开行的key
 * @param setTableExpantKeys 保存资产展开行的key
 * @returns
 */
export const useDataSourceTable = (
  dataRows: Record<string, any>[],
  dataSourceTable: Record<string, any>[],
  setDataSourceTable: (rows: Record<string, any>[]) => void,
  tableExpantKeys: string[],
  setTableExpantKeys: (keys: string[]) => void,
) => {
  /** 保存展开的key */
  const [tableExpandKey, setTableExpandKey] = useState<string>('');

  /** 处理子资产 */
  const asyncChildData = (pKey: string, childList: Record<string, any>[] | any) => {
    let dataList: Record<string, any>[] = [];
    dataSourceTable?.forEach((item: any) => {
      dataList?.push({
        ...item,
        children: item?.id == pKey ? childList : item?.children,
      });
    });
    setDataSourceTable(dataList);
  };

  /** 处理展开的表格key值 */
  const handleTableExpant = (open: boolean, clickKey: string) => {
    let openKeys: string[] = [...tableExpantKeys];
    if (open) {
      openKeys?.push(clickKey);
    } else {
      openKeys = tableExpantKeys?.filter((item: any) => item != clickKey);
    }
    setTableExpantKeys(openKeys);
  };

  /** 获取变更或解除资产个数回调 */
  const childManageCallback = (res: any) => {
    if (res && res?.msgFlag) {
      handleTableExpant(true, tableExpandKey);
      asyncChildData(tableExpandKey, res?.obj);
    } else {
      message.error(res?.msg);
    }
  };

  /**  获取管理页数据 */
  const { loading, getAssetListChildTableData } = assetListChildManageServices(childManageCallback);

  /** 初始化数据 */
  useEffect(() => {
    let dataList: Record<string, any>[] = [];
    if (dataRows?.length > 0) {
      dataRows?.forEach((item: any) => {
        dataList?.push({
          ...item,
          children: item?.resultantAsset ? [] : null,
        });
      });
    }
    setDataSourceTable(dataList);
    setTableExpantKeys([]);
  }, [dataRows]);

  /**处理展开关闭数据事件 */
  const onExpandTable = (expanded: boolean, record: Record<string, any>) => {
    if (expanded) {
      setTableExpandKey(record?.id);
      getAssetListChildTableData({
        id: record?.id,
      });
    } else {
      asyncChildData(record?.id, []);
      handleTableExpant(false, record?.id);
    }
  };

  return {
    onExpandTable,
    childLoading: loading,
  };
};
